import * as services from 'services/account';
import { routerRedux } from 'dva/router';
import { Toast } from 'antd-mobile';


const saveHid = (data) =>{
    sessionStorage.removeItem('hid');
    sessionStorage.setItem('hid', data);
}

const saveUserInfo = (data) => {
  localStorage.removeItem('auth'+sessionStorage.getItem("hid"));
  localStorage.setItem('auth'+sessionStorage.getItem("hid"), JSON.stringify(data));
};

const saveToken = (data) => {
  window.title = "sdf";
  //判断hid?
  if (data && data.length > 0) {

    if(/signin\?/.test(location.href) ){
    }
    sessionStorage.removeItem('token');
    sessionStorage.setItem('token', data);
  }
};

export default {
  namespace: 'account',

  state: {
    user: {},
    btn: "获取验证码",
    wait: 60, 
    gender: 0, 
    isDisabled: false,   
    clock: '',
    backGround: "#aa4929",
    badge: '',
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },

  effects: {
    * signin({ payload: { mobile, pswd, hospitalId } }, { call, put }){
        const login = yield call(services.signin, mobile, pswd, hospitalId);
        if(login.code == 200){
          Toast.success('登录成功', 2);
          yield saveUserInfo(login.data);
          yield put({type: 'save',payload: { user: login.data }});
          yield put(routerRedux.replace('/signin'));
        }else{
           Toast.fail('登录名或密码错误', 2);
        }
    },  

    *singauth({payload: { mobile, pswd }},{ call, put }){
      const data =yield call(services.signin, mobile , pswd);
      yield put({
        type: 'save',
        payload: {
          user: data,
        },
      });
      yield saveUserInfo(data.data);
    },

    * signup({ payload: data }, { call, put }) {
      const user = yield call(services.signup, data);
      yield put({
        type: 'save',
        payload: {
          user,
        },
      });
      yield saveUserInfo(user.data);
      Toast.success('注册成功', 2);
      
      yield put(routerRedux.replace('/healthy'));
    },

    * sendSmsCode({ payload: { mobile } }, { call, put }) {
      yield call(services.sendSmsCode, mobile.split(' ').join(''));
    },

    * registSmsCode({ payload: { mobile } }, { call, put }) {
      yield call(services.registSmsCode, mobile.split(' ').join(''));
    },

    * checkSmsCode({ payload: { mobile, code, redirectUrl } }, { call, put }) {
      mobile = mobile.split(' ').join('');
      let checks = yield call(services.checkSmsCode, mobile, code);
      if (redirectUrl && checks.code == 200) {
        yield put(
          routerRedux.push({
            pathname: redirectUrl,
            state: {
              mobile,
              code,
            },
          }),
        );
      }else{
         Toast.fail(checks.message, 2)
      }
    },

    * resetPassword({ payload: data }, { call, put }) {
      let reset = yield call(services.resetPassword, data);
      if(reset.code == 200){
        Toast.success('恭喜您，密码修改成功');
        yield put(routerRedux.replace('/signin'));
      }else{
        Toast.fail(reset.message);
      }

    },

    * signauth({ payload }, { call, put }) {
      const data = yield call(services.signauth);
      yield put({
        type: 'save',
        payload: {
          user: data,
        },
      });
      yield saveUserInfo(data.data);
      Toast.success('登录成功', 2);
      yield put(routerRedux.replace('/signin'));
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({pathname, query, ...rest }) => {
        // 服务端初始化给的token
        const token = query.temp_token;
        if (token) {
          saveToken(token);
        }
        // 服务端初始化给的跳转页面id
        const redirect = query.redirect;
        const hid = query.hid;
        if(hid){
          saveHid(hid);
        }
        if (redirect) {
          let url = '/doctor';
          if (redirect === '1') {
            url = '/doctor';
          } else if (redirect === '2') {
            url = '/healthy/articles';
          } else if (redirect === '3') {
            url = '/healthy'; //这个是科室介绍
          } 

          else if (redirect === '4') {
            url = '/healthy';
          } else if (redirect === '5') {
            url = '/healthy/archives';
          } else if (redirect === '6') {
            url = '/healthy'; //小儿推拿
          } else if (redirect === '7') {
            url = '/healthy/foods';
          } else if (redirect === '8') {
            url = '/settings/family';
          } 

          else if (redirect === '9') {
            url = '/healthy/archives/report';
          } else if (redirect === '10') {
            url = '/healthy/scale_record';
          } else if (redirect === '11') {
            url = '/healthy/diagnosis/scale';
          } else if (redirect === '12') {
            url = '/healthy/diagnosis/family';
          } else if (redirect === '13') {
            url = '/healthy';
          }
          sessionStorage.setItem('redirect', url);
        }
        const auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
        if (auth && /signin|signup/.test(pathname) ) {
          const url = sessionStorage.getItem('redirect') || '/healthy';
          dispatch(routerRedux.replace(url));
        }

        if (/signauth$/.test(pathname)) {
          dispatch({ type: 'signauth' });
        }
      });
    },
  },
};
